<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 *  Store Locator  Maitai Class
 *
 * 
 *
 * @package     CodeIgniter
 * @subpackage  Libraries
 * @category    Google Maps
 * @author      Carla Missiona
 * @link
 */


class Storelocator {

    /**
     * Constructor
     *
     * @access    public
     */
    function __construct()
    {
         $this->CI =& get_instance();  
    }
    function locateStore( $city, $town, $brgy, $area ,$prov ,$locator, $region=false ){
      $markers = false;
      $this->CI->load->model('store');    
       
      /* get client Location*/ 
      $this->CI =& get_instance();       
        if($locator == "nearest"){  
           if( preg_match('/City/' , $city ) != 1 ){
              $city = $city."City";
          } 
          $r =  $this->checkLocation($city, $town, $brgy, $area);            
          log_message("error", "CITY: " . $city . " -" . $r . "-asd ");
        //  log_message('error', 'Some variable did not contain a value.');
           if( $r == false ){      


          /* if location not in db */    
            $clientadd=""; $phil = "Philippines";
            /* compose clientadd  */  
            foreach(array($phil,$prov,$city,$brgy) as $k => $v ){   
                $s = str_replace(' ', '', $v);
                if(!empty($s) ){    
                   $v = preg_replace('/\s+/', '', $v);
                   $clientadd.=$v;
                   if( $k < 3 ){
                       $clientadd.="+";
                    }    
                 }
             } 
             
            /* fix for extra + */
            if(substr($clientadd,-1) == "+"){
                $clientadd = substr($clientadd,0,-1);                 
            } 

			//log_message("error", "CLIENTADD: " . $clientadd);
			
            $url = "https://maps.googleapis.com/maps/api/geocode/json?address=$clientadd";    
               //echo $clientadd;
               //echo $url; die();
           
            $curl = curl_init();
            // call google to query lat long ng client address 
            curl_setopt_array($curl, array(
                    CURLOPT_RETURNTRANSFER => 1,
                    CURLOPT_URL => $url
            ));
      
               $resp = curl_exec($curl);
               curl_close($curl);
               /* curl 4 lat long */
               $google = json_decode($resp); 
               $gl = get_object_vars($google); // this convert object to array
			   //log_message("error", "JSON RESPONSE: " . print_r($gl, true));
            
			
			
         /* store in db */         
         $b = false; $lat=$gl['results'][0]->geometry->location->lat; $lng=$gl['results'][0]->geometry->location->lng ; // $lname=str_replace("+", " ", $clientadd);
         $a = array($lat, $lng,$city, $town, $brgy, $area); 
         foreach($a as $k => $v){ 
           /*  replacing spaces or empty with NULL  */
           if( $v == " " || empty($v) ){
            $a[$k] = NULL;    
           }
         } 
        
         while( $b == false ){ 
             //while error in db try repeat below          
            $b = $this->CI->map->putsClientLoc($a[0],$a[1],$a[2],$a[3],$a[4],$a[5]); // [0] = lat [1] = lng [2] = city etc corresponds to map model , and line 82
         }
         
          /* query nearest store */     
          // $markers = $this->CI->map->getNeareststore($lat,$lng,35); // moved
          // 10152014 change radius ->getStore(lat,lang,rad) to 15 from [ before  $markers = $this->CI->store->getStore($lat,$lng,30); ]
          $radius = 10;
          do{
                $markers = $this->CI->store->getStore($lat,$lng,$radius); 
                if(is_array($markers) || $markers != false ){
                    break;
                }
                $radius += 2; 
            }while(!$markers);
          
         //echo "markers = = >";var_dump($markers); echo "<br>";  
         if(isset($gl['results'][0]->geometry->location->lat)){ 
           //die(" format 1 ");
           $m = array();
           array_push($m, array( "Lat" => $gl['results'][0]->geometry->location->lat));
           array_push($m, array( "Lng" => $gl['results'][0]->geometry->location->lng));
           array_push($m, array( "stores" => $markers));
           return $m;
           
           //return array( "Lat" => $gl['results'][0]->geometry->location->lat , "Lng" => $gl['results'][0]->geometry->location->lng , "stores" => $markers );
        }
        return " Error in user location input ";    
       } // end if not in db  
       else{  
           /*  if locations in db  call getNearest store  */  
           $n = array(); 
           foreach($r[0] as $k => $v){
              if($k == 'Lat' || $k == 'Lng' || $k == 'Longname'){
              array_push($n , array($k => $v ));
              }
           }   
          /* get markers or nearest stores */
          // var_dump($r); echo "<br>";       
             $radius = 10; // increment by 50
             do{
                $markers = $this->CI->store->getStore($r[0]["Lat"],$r[0]["Lng"],$radius);   
                if(is_array($markers) || $markers != false ) {
                    break;
                }                           
                $radius += 2; 
              }while(!$markers);
              $n['stores'] = $markers;  
           return $n ;        
         }
   } // end locator nearest 
    else if($locator == "preferred"){
 
      $r = trim($region);         
      $response = $this->CI->store->getStore(false,false,false,$r) ;
      if( $response == false ){
          /* returns nothing */
      }
      else{       
          return $response;     
      }
       
    }
     
  }// end function get client Location 
 
    function checkLocation( $city, $town, $brgy, $area ){  
      $a = array($city, $town, $brgy, $area) ;
      foreach($a as $k => $v){ 
         /*  replacing spaces or empty with NULL  */
         if( $v == " " || empty($v) ){
          $a[$k] = NULL;    
         }
      } 
        
     
      return $this->CI->map->getClientLatlong($a[0], $a[1], $a[2], $a[3] ); 
    }
    
}

/* End of file Googlemap.php */
/* Location: ./application/libraries/Googlemap.php */